package handlers

import (
	"strconv"
	"sysu-giep/internal/api/middleware"
	"sysu-giep/internal/database/models"
	"sysu-giep/internal/service"
	"sysu-giep/pkg/logger"
	"sysu-giep/pkg/response"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// UpdateProfileRequest 更新资料请求
type UpdateProfileRequest struct {
	RealName string `json:"real_name"`
	Phone    string `json:"phone"`
	Avatar   string `json:"avatar"`
}

// ChangePasswordRequest 修改密码请求
type ChangePasswordRequest struct {
	OldPassword string `json:"old_password" binding:"required"`
	NewPassword string `json:"new_password" binding:"required,min=6"`
}

// GetProfile 获取用户资料
// @Summary 获取用户资料
// @Description 获取当前登录用户的资料信息
// @Tags 用户
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.Response{data=map[string]interface{}}
// @Failure 401 {object} response.Response
// @Router /users/me [get]
func GetProfile(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)

	// 创建用户服务
	userService := service.NewUserService()

	// 从数据库获取用户详细信息
	user, err := userService.GetUserByID(userID)
	if err != nil {
		logger.ErrorLog("获取用户资料失败", logger.Error(err))
		response.InternalServerError(c, "获取用户资料失败")
		return
	}

	logger.Info("获取用户资料", zap.Uint64("user_id", uint64(userID)))

	// 构建响应数据
	profileData := gin.H{
		"id":         user.ID,
		"username":   user.Username,
		"email":      user.Email,
		"role":       user.Role,
		"status":     user.Status,
		"real_name":  user.RealName,
		"phone":      user.Phone,
		"avatar":     user.Avatar,
		"created_at": user.CreatedAt,
		"updated_at": user.UpdatedAt,
	}

	// 根据角色添加额外信息
	switch user.Role {
	case models.RoleEnterprise:
		if user.Enterprise != nil {
			profileData["enterprise"] = gin.H{
				"company_name":   user.Enterprise.CompanyName,
				"industry":       user.Enterprise.Industry,
				"company_size":   user.Enterprise.CompanySize,
				"contact_person": user.Enterprise.ContactPerson,
				"contact_phone":  user.Enterprise.ContactPhone,
				"address":        user.Enterprise.Address,
				"description":    user.Enterprise.Description,
				"website":        user.Enterprise.Website,
			}
		}
	case models.RoleTutor:
		if user.Tutor != nil {
			profileData["tutor"] = gin.H{
				"title":          user.Tutor.Title,
				"department":     user.Tutor.Department,
				"research_field": user.Tutor.ResearchField,
				"education":      user.Tutor.Education,
				"experience":     user.Tutor.Experience,
				"introduction":   user.Tutor.Introduction,
			}
		}
	case models.RoleStudent:
		if user.Student != nil {
			profileData["student"] = gin.H{
				"student_id":     user.Student.StudentID,
				"major":          user.Student.Major,
				"grade":          user.Student.Grade,
				"degree":         user.Student.Degree,
				"research_field": user.Student.ResearchField,
				"introduction":   user.Student.Introduction,
			}
		}
	}

	response.Success(c, profileData)
}

// UpdateProfile 更新用户资料
// @Summary 更新用户资料
// @Description 更新当前登录用户的资料信息
// @Tags 用户
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body UpdateProfileRequest true "用户资料"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Router /users/me [put]
func UpdateProfile(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)

	var req UpdateProfileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误: "+err.Error())
		return
	}

	// 创建用户服务
	userService := service.NewUserService()

	// 构建更新数据
	updates := make(map[string]interface{})
	if req.RealName != "" {
		updates["real_name"] = req.RealName
	}
	if req.Phone != "" {
		updates["phone"] = req.Phone
	}
	if req.Avatar != "" {
		updates["avatar"] = req.Avatar
	}

	// 更新用户资料
	if err := userService.UpdateUser(userID, updates); err != nil {
		logger.ErrorLog("更新用户资料失败", logger.Error(err))
		response.InternalServerError(c, "更新用户资料失败")
		return
	}

	logger.Info("更新用户资料成功", zap.Uint64("user_id", uint64(userID)))

	response.SuccessWithMessage(c, "资料更新成功", nil)
}

// ChangePassword 修改密码
// @Summary 修改密码
// @Description 修改当前登录用户的密码
// @Tags 用户
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body ChangePasswordRequest true "密码信息"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Router /users/me/password [put]
func ChangePassword(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)

	var req ChangePasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误: "+err.Error())
		return
	}

	// 创建用户服务
	userService := service.NewUserService()

	// 修改密码
	if err := userService.ChangePassword(userID, req.OldPassword, req.NewPassword); err != nil {
		logger.ErrorLog("修改密码失败", logger.Error(err))
		response.BadRequest(c, err.Error())
		return
	}

	logger.Info("修改密码成功", zap.Uint64("user_id", uint64(userID)))

	response.SuccessWithMessage(c, "密码修改成功", nil)
}

// GetUserByID 根据ID获取用户信息
// @Summary 根据ID获取用户信息
// @Description 根据用户ID获取用户详细信息
// @Tags 用户
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "用户ID"
// @Success 200 {object} response.Response{data=map[string]interface{}}
// @Failure 404 {object} response.Response
// @Router /users/{id} [get]
func GetUserByID(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "无效的用户ID")
		return
	}

	// 创建用户服务
	userService := service.NewUserService()

	// 从数据库获取用户信息
	user, err := userService.GetUserByID(uint(id))
	if err != nil {
		logger.ErrorLog("获取用户信息失败", logger.Error(err))
		response.NotFound(c, "用户不存在")
		return
	}


	// 构建响应数据（不包含敏感信息）
	userData := gin.H{
		"id":         user.ID,
		"username":   user.Username,
		"real_name":  user.RealName,
		"role":       user.Role,
		"status":     user.Status,
		"avatar":     user.Avatar,
		"created_at": user.CreatedAt,
	}

	// 根据角色添加额外信息
	switch user.Role {
	case models.RoleEnterprise:
		if user.Enterprise != nil {
			userData["enterprise"] = gin.H{
				"company_name": user.Enterprise.CompanyName,
				"industry":     user.Enterprise.Industry,
				"company_size": user.Enterprise.CompanySize,
				"description":  user.Enterprise.Description,
				"website":      user.Enterprise.Website,
			}
		}
	case models.RoleTutor:
		if user.Tutor != nil {
			userData["tutor"] = gin.H{
				"title":          user.Tutor.Title,
				"department":     user.Tutor.Department,
				"research_field": user.Tutor.ResearchField,
				"introduction":   user.Tutor.Introduction,
			}
		}
	case models.RoleStudent:
		if user.Student != nil {
			userData["student"] = gin.H{
				"major":          user.Student.Major,
				"grade":          user.Student.Grade,
				"research_field": user.Student.ResearchField,
				"introduction":   user.Student.Introduction,
			}
		}
	}

	response.Success(c, userData)
}
